﻿

-- =============================================
-- Author:		Popa Dorin
-- Create date: 08.04.2014
-- Description:	schimba numele contuui
-- =============================================
CREATE PROCEDURE [dbo].[balcon_ChangeCont] 
	@OldCont dbo.TipCont, 
	@NewCont dbo.TipCont,
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	BEGIN TRAN
    -- Dezactiveaza Triggerii
	ALTER TABLE dbo.Conturi NOCHECK CONSTRAINT FK_Conturi_Conturi
	ALTER TABLE dbo.Rulaje NOCHECK CONSTRAINT FK_Rulaje_ConturiDebit
	ALTER TABLE dbo.Rulaje NOCHECK CONSTRAINT FK_Rulaje_ConturiCredit
	ALTER TABLE dbo.ConturiCoresp NOCHECK CONSTRAINT FK_ConturiCoresp_Conturi
	ALTER TABLE dbo.ConturiCoresp NOCHECK CONSTRAINT FK_ConturiCoresp_Conturi1
	ALTER TABLE dbo.Conturispeciale NOCHECK CONSTRAINT FK_ConturiSpeciale_Conturi

	UPDATE Rulaje SET ContDebit = @NewCont WHERE ContDebit = @OldCont AND CodUnitate=@CodUnitate
	IF @@ERROR != 0 GOTO EROARE	
	UPDATE Rulaje SET ContCredit = @NewCont WHERE ContCredit = @OldCont AND CodUnitate=@CodUnitate
	IF @@ERROR != 0 GOTO EROARE	
	UPDATE Conturi SET ContParinte = @NewCont WHERE ContParinte=@OldCont AND CodUnitate=@CodUnitate
	IF @@ERROR != 0 GOTO EROARE	
	UPDATE ConturiCoresp SET ContDebit=@NewCont WHERE ContDebit =@OldCont AND CodUnitate=@CodUnitate
	IF @@ERROR != 0 GOTO EROARE	
	UPDATE ConturiCoresp SET ContCredit=@NewCont WHERE ContCredit =@OldCont AND CodUnitate=@CodUnitate
	IF @@ERROR != 0 GOTO EROARE	
	UPDATE ConturiSpeciale SET Cont = @NewCont WHERE Cont=@OldCont AND CodUnitate=@CodUnitate
	IF @@ERROR != 0 GOTO EROARE
	IF NOT EXISTS(SELECT * FROM Conturi WHERE CodUnitate=@CodUnitate and Cont=@NewCont)	
		UPDATE Conturi SET Cont = @NewCont WHERE Cont=@OldCont AND CodUnitate=@CodUnitate
	ELSE
		DELETE Conturi WHERE Cont=@OldCont AND CodUnitate=@CodUnitate
	
	IF @@ERROR != 0 GOTO EROARE	
	 -- Activeaza Triggerii
	ALTER TABLE dbo.Conturi CHECK CONSTRAINT FK_Conturi_Conturi
	ALTER TABLE dbo.Rulaje CHECK CONSTRAINT FK_Rulaje_ConturiDebit
	ALTER TABLE dbo.Rulaje CHECK CONSTRAINT FK_Rulaje_ConturiCredit
	ALTER TABLE dbo.ConturiCoresp CHECK CONSTRAINT FK_ConturiCoresp_Conturi
	ALTER TABLE dbo.ConturiCoresp CHECK CONSTRAINT FK_ConturiCoresp_Conturi1
	ALTER TABLE dbo.ConturiSpeciale CHECK CONSTRAINT FK_ConturiSpeciale_Conturi

	COMMIT

	GOTO Gata
	EROARE:
		ROLLBACK
		RAISERROR ('Eroare schimbarea numelui contului!',16,-1)
		GOTO Gata

	Gata:
END